package fr.neyb.wesb.core.data.compare;

import java.util.Comparator;

import fr.neyb.framework.exceptions.TechnicalException;
import fr.neyb.wesb.core.data.content.Field;

public abstract class AbstractFieldComparator<T extends Field> implements
		Comparator<Field> {

	private final Class<T> clazz;
	private final Order order;

	public AbstractFieldComparator(Class<T> clazz, Order order) {
		this.clazz = clazz;
		this.order = order;
	}

	@Override
	public final int compare(Field o1, Field o2) {
		if (clazz.isInstance(o1) && clazz.isInstance(o2)) {
			int result = PreCheckedCompare(clazz.cast(o1), clazz.cast(o2));
			switch (order) {
			case Ascendant:
				return result;
			case Descendant:
				return -1 * result;
			default:
				throw new TechnicalException("unsupported order : " + order);
			}
		} else {
			throw new TechnicalException("invalid use of " + getClass());
		}
	}

	protected abstract int PreCheckedCompare(T o1, T o2);

}
